package proyecto.testcasetool.presentation.editor.pages;

/*******************************************************************************
 * Copyright (c) 2008, 2012 Obeo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Obeo - initial API and implementation
 *******************************************************************************/

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.forms.widgets.FormToolkit;

import proyecto.testcasetool.presentation.treemaster.CommandParameter;


/**
 * @author <a href="mailto:goulwen.lefur@obeo.fr">Goulwen Le Fur</a>
 */
public class MasterPartUseCase extends AbstractMasterPart implements ISelectionChangedListener {

	private List<CommandParameter> commandParameters;

	private EObject modelRoot;

	private EditingDomain editingDomain;

	private EObject selectedObject;

	/**
	 * @param managedForm
	 *            the form where this part will be
	 * @param container
	 *            the composite where to create the part
	 * @param block
	 *            the AbstractEEFMasterDetailsBlock which will contain this part
	 */
	public MasterPartUseCase(FormToolkit toolkit, Composite container, AbstractMasterDetailsBlock block) {
		super(toolkit, container, block);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.emf.eef.runtime.ui.widgets.masterdetails.AbstractEEFMasterPart#createSectionClientContents(org.eclipse.swt.widgets.Composite,
	 *      org.eclipse.ui.forms.widgets.FormToolkit)
	 */
	protected TreeViewer createSectionClientContents(Composite sectionContainer, FormToolkit toolkit) {
		Tree tree = toolkit.createTree(sectionContainer, SWT.MULTI | SWT.BORDER);
		TreeViewer result = new TreeViewer(tree);
		result.setContentProvider(new AdapterFactoryContentProvider(getAdapterFactory()));
		result.setLabelProvider(new AdapterFactoryLabelProvider(getAdapterFactory()));
		GridData gd = new GridData(GridData.FILL_BOTH);
		gd.widthHint = 50;
		gd.heightHint = 80;
		tree.setLayoutData(gd);
		
		result.addSelectionChangedListener(this);
		return result;
	}

	/**
	 * @return the list of command parameters
	 */
	public List<CommandParameter> getCommandParameter() {
		if (commandParameters == null) {
			createCommandParameters(modelRoot);
		}
		return commandParameters;
	}

	/**
	 * initialize the command parameters. If this method is called whether command parameters are already
	 * initialized, old values will be erased
	 */
	private void createCommandParameters(EObject object) {
		if (object == null) {
			commandParameters = new ArrayList<CommandParameter>();
		} else {
			commandParameters = new ArrayList<CommandParameter>();
			for (EReference reference : object.eClass().getEAllReferences()) {
				if (!reference.isContainment()) {
					// Create command parameter for containment references only.
					continue;
				} else {
					commandParameters.add(new CommandParameter(reference, reference.getEReferenceType()));
				}
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void createSectionClient(Composite sectionContainer, FormToolkit toolkit) {
		sectionContainer.setLayout(new GridLayout());
		createModelRoot();
		createModelViewer(sectionContainer, toolkit);
	}

	/**
	 * initialize model root
	 */
	private void createModelRoot() {
		editingDomain = getBlock().getEditingDomain();
		if (editingDomain instanceof AdapterFactoryEditingDomain) {
			AdapterFactoryEditingDomain afed = (AdapterFactoryEditingDomain)editingDomain;
			EList<Resource> resources = afed.getResourceSet().getResources();
			if (resources != null && resources.size() != 0) {
				// Assuming the main resource is the first resource
				Resource resource = resources.get(0);
				if (resource.getContents() != null && resource.getContents().size() > 0) {
					modelRoot = resource.getContents().get(0);
					selectedObject = modelRoot;
				}
			}
		}
	}


	/**
	 * Create the TreeView container
	 * 
	 * @param sectionContainer
	 * @param toolkit
	 */
	private void createModelViewer(Composite sectionContainer, FormToolkit toolkit) {
		Composite modelViewerComposite = new Composite(sectionContainer, SWT.NONE);
		modelViewerComposite.setLayout(FormLayoutFactory.createMasterGridLayout(false, 1));
		modelViewerComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
		// TODO Arreglo de layout
		//FormLayoutFactory.visualizeLayoutArea(modelViewerComposite, 5);
		super.createSectionClient(modelViewerComposite, toolkit);
	}

	// Este metodo se usa para crear el menu que se va a mostrar cuando se selecciona el boton de
	// toolbar del tree
	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		IStructuredSelection selection = (IStructuredSelection)event.getSelection();
		if (selection instanceof EObject){
			selectedObject = (EObject)selection.getFirstElement();
			createCommandParameters(selectedObject);
		}
	}

}

